package com.srwl.mytx.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Scroller;
import android.widget.TextView;

import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.R;
import com.srwl.mytx.utils.GlideLoadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dahai2070 on 2018/4/22 0022.
 */

public class ConnectInfiniteView extends FrameLayout implements View.OnClickListener {
    private String TAG = "ConnectInfiniteView";
    private int verticalMinDistance = 20;
    private Contact contact;
    private ImageView iv_avatar;
    private TextView tv_name;
    private Context context;
    private float mPosX;
    private float mPosY;
    private float mCurPosX;
    private float mCurPosY;
    private Scroller mScroller;
    View ll_buttonView;
    private ViewDragHelper dragHelper;
    private int orignalRootViewWidth;
    private ViewGroup.LayoutParams layoutParams;
    private boolean bol_clickEvent;
    private TextView mLocationButton;
    private TextView mChatButton;
    private boolean spreadChildItem = false;
    private int childItemsTopY = -1;
    private int childItemsBottomY = -1;
    private List<ConnectInfiniteView> connectInfiniteViewList;
    private ConnectInfiniteView parentInfiniteView;

    private int baseLineY;
    private int layer;
    private LingLineView LingLineView;

    public ConnectInfiniteView(Context context) {
        super(context);
    }

    public ConnectInfiniteView(Context context, Contact contact) {
        super(context);
        this.context = context;
        this.contact = contact;

        //  setupView(context);
    }

    public ConnectInfiniteView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // setupView(context);

    }

    public ConnectInfiniteView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // setupView(context);

    }

    public void init() {
        LayoutInflater.from(context).inflate(R.layout.connect_infinite_layout, this);
        ll_buttonView = findViewById(R.id.ll_button);
        iv_avatar = findViewById(R.id.iv_avatar);
        tv_name = findViewById(R.id.tv_nick);
        mLocationButton = findViewById(R.id.btn_location);
        mLocationButton.setOnClickListener(this);
        mChatButton = findViewById(R.id.btn_chat);
        mChatButton.setOnClickListener(this);
        findViewById(R.id.btn_chat);
        int childCount = getChildCount();
        mScroller = new Scroller(getContext());
        if (contact != null && contact.getTargetUser() != null) {
            //Glide.with(context).load(contact.getUser().getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_avatar);
            GlideLoadUtils.glideLoad(context,contact.getTargetUser().getAvatar(),iv_avatar);
            tv_name.setText(contact.getTargetUser().getUsername());
        }
        initDragCallBack();

    }

    private void initDragCallBack() {

        ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {

            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                return true;
            }


            @Override
            public int clampViewPositionHorizontal(View child, int left, int dx) {
                // Log.d(TAG, "clampViewPositionHorizontal: " + left);
                if (left > 0) {
                    left = 0;
                } else if (left < -ll_buttonView.getWidth()) {
                    left = -ll_buttonView.getWidth();
                }
                return left;
            }

            @Override
            public void onViewReleased(View releasedChild, float xvel, float yvel) {
                if (xvel == 0) {
                    if (releasedChild.getLeft() < -ll_buttonView.getWidth() / 2) {
                        close();

                    } else {
                        open();
                    }
                } else if (xvel < 0) {
                    close();
                } else {
                    open();
                }
            }

            @Override
            public int getViewHorizontalDragRange(View child) {
                return child.getWidth();
            }

            @Override
            public int getViewVerticalDragRange(View child) {
                return child.getHeight();
            }
            //            @Override
//            public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
//
////                float x = ll_buttonView.getWidth();
////                if (Math.abs( left)<x/2){
////                    mScroller.startScroll(getScrollX(),getScrollY(),Math.abs( left),0);
////                    invalidate();
////                }
////                Log.d(TAG, "onViewPositionChanged: "+x);
////                if (x + left + iv_avatar.getWidth() > orignalRootViewWidth) {
////
////                    layoutParams.width = (int) (x + left + iv_avatar.getWidth());
////                    setLayoutParams(layoutParams);
////                } else if (getWidth()!=orignalRootViewWidth){
////                    layoutParams.width = orignalRootViewWidth;
////                    setLayoutParams(layoutParams);
////                }
//            }
        };
        dragHelper = ViewDragHelper.create(this, 1.0f, callback);

    }

    private void close() {
        dragHelper.smoothSlideViewTo(getChildAt(0), -ll_buttonView.getWidth(), 0);
        ViewCompat.postInvalidateOnAnimation(this);
    }

    private void open() {
        dragHelper.smoothSlideViewTo(getChildAt(0), 0, 0);
        ViewCompat.postInvalidateOnAnimation(this);
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return dragHelper.shouldInterceptTouchEvent(ev);
    }

//    @Override
//    public boolean onInterceptHoverEvent(MotionEvent event) {
//        return dragHelper.shouldInterceptTouchEvent(event);
//    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        dragHelper.processTouchEvent(event);
        // event.getX(); //相当于当前view 的左上角的X坐标（相对坐标）
        //  event.getRawX();//相对于屏幕左上角的X坐标（绝对坐标）
        //如果一次屏幕点击事件序列中没有滑动事件，认定为一次点击事件
        // int action = event.getAction();
//        switch (action) {
//            case MotionEvent.ACTION_DOWN:
//                bol_clickEvent = true;
//                break;
//            case MotionEvent.ACTION_MOVE:
//                bol_clickEvent = false;
//                break;
//            case MotionEvent.ACTION_UP:
//                if (bol_clickEvent) {
//                    callOnClick();
//                }
//                break;
//        }
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//        left -= getChildAt(0).getWidth();
        super.onLayout(changed, left, top, right, bottom);
        View childAt = getChildAt(0);
        orignalRootViewWidth = getWidth();
        layoutParams = getLayoutParams();
        childAt.layout(-ll_buttonView.getWidth(), 0, childAt.getWidth() - ll_buttonView.getWidth(), childAt.getHeight());

    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (dragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_chat:


                break;

            case R.id.btn_location:

                break;
        }
    }

    public void setGetMoreContactClickListener(OnClickListener listener) {
        findViewById(R.id.rl_get_more_contact).setOnClickListener(listener);
    }

    public int getChildItemsTopY() {
        return childItemsTopY;
    }

    public void setChildItemsTopY(int childItemsTopY) {
        this.childItemsTopY = childItemsTopY;
    }

    public int getChildItemsBottomY() {
        return childItemsBottomY;
    }

    public void setChildItemsBottomY(int childItemsBottomY) {
        this.childItemsBottomY = childItemsBottomY;
    }


    public List<ConnectInfiniteView> getConnectInfiniteViewList() {

        return connectInfiniteViewList;
    }

    public void setConnectInfiniteViewList(List<ConnectInfiniteView> connectInfiniteViewList) {
        if (this.connectInfiniteViewList == null) this.connectInfiniteViewList = new ArrayList<>();
        this.connectInfiniteViewList.addAll(connectInfiniteViewList);
    }

    public void addChildConnectInfiniteView(ConnectInfiniteView childView) {
        if (this.connectInfiniteViewList == null) this.connectInfiniteViewList = new ArrayList<>();
        connectInfiniteViewList.add(childView);
    }

    public void romoveChildConnectInfiniteView(ConnectInfiniteView childView) {
        connectInfiniteViewList.remove(childView);
    }

    public boolean isSpreadChildItem() {
        return spreadChildItem;
    }

    public void setSpreadChildItem(boolean spreadChildItem) {
        this.spreadChildItem = spreadChildItem;
    }


    public int getBaseLineY() {
        return baseLineY;
    }

    public void setBaseLineY(int baseLineY) {
        this.baseLineY = baseLineY;
    }


    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public ConnectInfiniteView getParentInfiniteView() {
        return parentInfiniteView;
    }

    public void setParentInfiniteView(ConnectInfiniteView parentInfiniteView) {
        this.parentInfiniteView = parentInfiniteView;
    }

    public int getLayer() {
        return layer;
    }

    public void setLayer(int layer) {
        this.layer = layer;
    }

    public LingLineView getLingLineView() {
        return LingLineView;
    }

    public void setLingLineView(LingLineView LingLineView) {
        this.LingLineView = LingLineView;
    }
}
